/*
    rpc调用客户端测试：业务层与网络层联合测试
*/
#include "../../common/net.hpp"
#include "../../common/dispatcher.hpp"
#include "../../client/rpc_caller.hpp"
#include <thread>

void callback(const Json::Value &result)
{
    std::cout << "callback result: " << result << std::endl;
}

int main()
{
    SetDefaultLogLevel(Level::INFO);
    // 1.定义Requestor(请求管理器) && RpcCaller（rpc调用器）
    ns_jsonrpc::ns_client::Requestor::RequestorPtr requestor = std::make_shared<ns_jsonrpc::ns_client::Requestor>();
    ns_jsonrpc::ns_client::RpcCaller::RpcCallerPtr rpcCaller = std::make_shared<ns_jsonrpc::ns_client::RpcCaller>(requestor);

    // 2.定义Dispatcher(调度器) && 注册响应回调（回调由上一层请求管理器Requestor提供）
    ns_jsonrpc::Dispatcher::DispatcherPtr dp = std::make_shared<ns_jsonrpc::Dispatcher>();
    auto rpcRsqCb = std::bind(&ns_jsonrpc::ns_client::Requestor::onResponse, requestor.get(), std::placeholders::_1, std::placeholders::_2);
    dp->registerCallback<ns_jsonrpc::BaseMessage>(ns_jsonrpc::MType::RSP_RPC, rpcRsqCb);

    // 3.定义客户端服务 && 注册响应回调（回调由上一层调度器Dispatcher提供）
    ns_jsonrpc::BaseClient::BaseClientPtr ct = ns_jsonrpc::MuduoClientFactory::create("127.0.0.1", 8888);
    ns_jsonrpc::MessageCallback cb = std::bind(&ns_jsonrpc::Dispatcher::onMessage, dp.get(), std::placeholders::_1, std::placeholders::_2);
    ct->setMessageCallback(cb);

    // 4.连接服务器
    ct->connect();

    // 5.发送rpc请求
    // // 5.1 同步请求
    // Json::Value params;
    // params["num1"] = 1;
    // params["num2"] = 1;
    // Json::Value result;
    // rpcCaller->call(ct->connection(), "add", params, result);
    // std::cout << "sync result: " << result << std::endl; // 打印结果

    // 5.2 异步请求
    Json::Value params2;
    params2["num1"] = 2;
    params2["num2"] = 2;
    ns_jsonrpc::ns_client::RpcCaller::JsonAsyncResponse result2;
    rpcCaller->call(ct->connection(), "add", params2, result2);
    std::thread td([&result2](){
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::cout << "[son thread] async result: " << result2.get() << std::endl;
    });
    std::cout << "[father thread] wait... " << std::endl; // 打印结果
    std::this_thread::sleep_for(std::chrono::seconds(20));

    // // 5.3 回调
    // Json::Value params3;
    // params3["num1"] = 3;
    // params3["num2"] = 3;
    // rpcCaller->call(ct->connection(), "add", params3, callback);
    // std::this_thread::sleep_for(std::chrono::seconds(20));
    return 0;
}